package com.alibaba.dongbao.utils.code;

import com.sun.xml.internal.messaging.saaj.util.ByteOutputStream;
import lombok.Data;
import javax.imageio.ImageIO;
import javax.imageio.stream.ImageOutputStream;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.Random;

/**
 * @Author: Mr.ZJW
 * @Date: 2022-04-20 8:59
 * @Description: 二维码图形工具
 */
@Data
public class ImageCode {

    //图形内容
    public String code;
    //图片
    public ByteArrayInputStream image;
    //宽
    private int wight = 400;
    //高
    private int height = 100;

    public static ImageCode getInstance() {
        return new ImageCode();
    }

    public ImageCode() {
        //图形缓冲区
        BufferedImage image = new BufferedImage(wight, height, BufferedImage.TYPE_3BYTE_BGR);
        //画笔
        Graphics graphics = image.getGraphics();
        //设置颜色
        graphics.setColor(new Color(46, 173, 144));
        //画矩形
        graphics.fillRect(0, 0, wight, height);
        //设置字体
        graphics.setFont(new Font("宋体", Font.PLAIN, 30));
        //设置随机数
        Random random = new Random();
        //算数验证码
        int num1 = random.nextInt(20);
        int num2 = random.nextInt(20);
        //设置颜色
        graphics.setColor(new Color(2, 0, 0));
        //画图
        int Y = 60;
        graphics.drawString(String.valueOf(num1), wight / 6 * 0 + 50, Y);
        graphics.drawString("+", wight / 6 * 1 + 50, Y);
        graphics.drawString(String.valueOf(num2), wight / 6 * 2 + 50, Y);
        graphics.drawString("=", wight / 6 * 3 + 50, Y);
        graphics.drawString("?", wight / 6 * 4 + 50, Y);
        //计算值
        int result = num1 + num2;
        this.code = result+"";
        //收笔
        graphics.dispose();

        ByteArrayInputStream inputStream = null;
        ByteOutputStream outputStream = new ByteOutputStream();

        //赋值给ByteArrayInputStream
        try {
            ImageOutputStream imageOutputStream = ImageIO.createImageOutputStream(outputStream);
            ImageIO.write(image, "jpg", imageOutputStream);

            inputStream = new ByteArrayInputStream(outputStream.toByteArray());
        } catch (IOException e) {
            e.printStackTrace();
        }
        //生成图片
        this.image = inputStream;
    }


}
